import { Mat4, Node, UITransform, v3, Vec3, view } from 'cc';
import { JiuJiuXiaoDongWu_GameStorage } from './JiuJiuXiaoDongWu_GameStorage';

export class JiuJiuXiaoDongWu_GameData {
    // static row: number = 4; // 行数
    // static col: number = 4; // 列数

    static item_撤回_number: number = 10;
    static item_翻转_number: number = 10;
    static item_撤回_add_number: number = 10;
    static item_翻转_add_number: number = 10;

    static InitData() {

    }

    // 关卡从1开始
    static Get_level() {
        return JiuJiuXiaoDongWu_GameStorage.data.mode_1.level;
    }

    static Set_level(_level) {
        JiuJiuXiaoDongWu_GameStorage.data.mode_1.level = _level;
        JiuJiuXiaoDongWu_GameStorage.saveData();
    }

    // 难度范围映射
    static difficultyRanges = [
        { min: 3, max: 9 },   // 难度1
        { min: 5, max: 14 },   // 难度2
        { min: 7, max: 18 },  // 难度3
        { min: 9, max: 20 },  // 难度4
        { min: 11, max: 25 }   // 难度5
    ];

    // 根据关卡获取数量
    static getQuantityByLevel(level: number): number {
        const baseDifficulty = (level - 1) % 5;  // 0-4 对应难度1-5
        const cycleNum = Math.floor((level - 1) / 5);

        // 计算实际数值：基础值 + 循环增长
        const range = this.difficultyRanges[baseDifficulty];
        const progress = Math.min(cycleNum * 0.2, 1); // 每循环增长20%，最大100%
        let value = range.min + (range.max - range.min) * progress;

        return Math.floor(value);
    }




    static getCountByLevel(level: number, rise: number, fall: number, start: number = 3): number {
        const cycle = rise + fall;                  // 一个完整周期
        const posInCycle = (level - 1) % cycle;    // 在周期中的位置
        const numCycles = Math.floor((level - 1) / cycle); // 已经完成的周期数

        let value;
        if (posInCycle < rise) {
            // 上升阶段
            value = start + numCycles * fall + posInCycle;
        } else {
            // 回落阶段
            value = start + numCycles * fall + rise - (posInCycle - rise + 1);
        }

        return value;
    }

    static getCountByLevelWithMax(
        level: number,
        rise: number = 3,
        fall: number = 1,
        start: number = 3,
        maxValue: number = 25,
        maxFluctuation: number = 2
    ): number {
        // 先计算基础 count
        let count = JiuJiuXiaoDongWu_GameData.getCountByLevel(level, rise, fall, start);

        // 如果超过最大值
        if (count >= maxValue) {
            // 保证最高点随机一点波动，不固定
            count = maxValue - Math.floor(Math.random() * maxFluctuation);
        }

        return count;
    }

    // // 测试前 30 个关卡
    // for (let i = 1; i <= 30; i++) {
    //     console.log(`Level ${i}: count = ${getCountByLevelWithMax(i, 3, 1, 3, 25, 2)}`);
    // }

    // static ClearData() {
    // }


    static margin: number = 40;

    /**
     * 考虑父物体旋转的适配屏幕
     */
    static fitToScreenWithRotation(父物体) {
        const screenSize = view.getVisibleSize();
        const children = 父物体.children;

        if (children.length === 0) return;

        // 1. 计算考虑旋转后的视觉包围盒
        const visualBounds = this.calculateVisualBounds(children, 父物体);

        // 2. 计算缩放比例
        const availableWidth = screenSize.width - this.margin * 2;
        const availableHeight = screenSize.height - this.margin * 2;

        const scaleX = availableWidth / visualBounds.width;
        const scaleY = availableHeight / visualBounds.height;

        // 3. 只有需要缩小时才缩放
        let targetScale = 1;
        if (scaleX < 1 || scaleY < 1) {
            targetScale = Math.min(scaleX, scaleY);
        }

        // 4. 应用缩放
        父物体.setScale(targetScale, targetScale, 1);

        // console.log(`视觉包围盒: ${visualBounds.width} x ${visualBounds.height}, 缩放: ${targetScale}`);
    }

    /**
     * 计算考虑旋转后的视觉包围盒（世界坐标系）
     */
    /**
   * 计算考虑旋转后的视觉包围盒（在父物体坐标系中）
   */
    static calculateVisualBounds(children: Node[], 父物体): { width: number, height: number } {
        let minX = Infinity, maxX = -Infinity;
        let minY = Infinity, maxY = -Infinity;

        // 父物体的旋转角度（弧度）
        const parentAngle = 父物体.eulerAngles.z * Math.PI / 180;
        const cosA = Math.cos(parentAngle);
        const sinA = Math.sin(parentAngle);

        children.forEach(child => {
            const uiTransform = child.getComponent(UITransform);
            if (uiTransform) {
                const childPos = child.position;
                const width = uiTransform.width;
                const height = uiTransform.height;
                const anchorX = uiTransform.anchorX;
                const anchorY = uiTransform.anchorY;

                // 计算子物体四个角点在父物体坐标系中的位置（不考虑父物体旋转）
                const localCorners = [
                    v3(childPos.x - width * anchorX, childPos.y - height * anchorY, 0), // 左下
                    v3(childPos.x + width * (1 - anchorX), childPos.y - height * anchorY, 0), // 右下
                    v3(childPos.x - width * anchorX, childPos.y + height * (1 - anchorY), 0), // 左上
                    v3(childPos.x + width * (1 - anchorX), childPos.y + height * (1 - anchorY), 0) // 右上
                ];

                // 应用父物体旋转到每个角点
                localCorners.forEach(corner => {
                    // 绕父物体原点旋转
                    const rotatedX = corner.x * cosA - corner.y * sinA;
                    const rotatedY = corner.x * sinA + corner.y * cosA;

                    minX = Math.min(minX, rotatedX);
                    maxX = Math.max(maxX, rotatedX);
                    minY = Math.min(minY, rotatedY);
                    maxY = Math.max(maxY, rotatedY);
                });
            }
        });

        // console.log("旋转后包围盒:", { minX, maxX, minY, maxY, width: maxX - minX, height: maxY - minY });

        return {
            width: maxX - minX,
            height: maxY - minY
        };
    }

    /**
     * 计算UI物体的四个角点（局部坐标系）
     */
    static calculateLocalCorners(uiTransform: UITransform): Vec3[] {
        const width = uiTransform.width;
        const height = uiTransform.height;
        const anchorX = uiTransform.anchorX;
        const anchorY = uiTransform.anchorY;

        // 计算基于锚点的四个角点
        const left = -width * anchorX;
        const right = left + width;
        const bottom = -height * anchorY;
        const top = bottom + height;

        return [
            v3(left, bottom, 0),   // 左下
            v3(right, bottom, 0),  // 右下
            v3(left, top, 0),      // 左上
            v3(right, top, 0)      // 右上
        ];
    }




    /**
    * 水平居中父物体
    */

    /**
     * 水平居中父物体
     */
    static centerHorizontally(父物体: Node) {
        const screenSize = view.getVisibleSize();
        const children = 父物体.children;

        if (children.length === 0) return;

        // 计算局部坐标系中的水平边界
        const localBounds = this.calculateLocalHorizontalBounds(children, 父物体);

        // 计算局部中心点偏移
        const localCenterX = (localBounds.minX + localBounds.maxX) / 2;
        const worldOffsetX = -localCenterX;

        // 应用位移（保持当前世界位置的Y轴不变）
        const currentPos = 父物体.getPosition();
        父物体.setPosition(currentPos.x + worldOffsetX, currentPos.y, currentPos.z);

        // console.log(`水平居中: 局部中心X=${localCenterX}, 偏移X=${worldOffsetX}`);
    }

    /**
     * 计算局部坐标系中的水平边界（考虑旋转）
     */
    static calculateLocalHorizontalBounds(children: Node[], 父物体: Node): { minX: number, maxX: number } {
        let minX = Infinity, maxX = -Infinity;

        const parentAngle = 父物体.eulerAngles.z * Math.PI / 180;
        const cosA = Math.cos(parentAngle);
        const sinA = Math.sin(parentAngle);

        children.forEach(child => {
            const uiTransform = child.getComponent(UITransform);
            if (uiTransform) {
                const childPos = child.position;
                const width = uiTransform.width;
                const height = uiTransform.height;
                const anchorX = uiTransform.anchorX;
                const anchorY = uiTransform.anchorY;

                // 子物体自身的旋转角度
                const childAngle = child.eulerAngles.z * Math.PI / 180;
                const cosChild = Math.cos(childAngle);
                const sinChild = Math.sin(childAngle);

                const localCorners = [
                    v3(childPos.x - width * anchorX, childPos.y - height * anchorY, 0),
                    v3(childPos.x + width * (1 - anchorX), childPos.y - height * anchorY, 0),
                    v3(childPos.x - width * anchorX, childPos.y + height * (1 - anchorY), 0),
                    v3(childPos.x + width * (1 - anchorX), childPos.y + height * (1 - anchorY), 0)
                ];

                localCorners.forEach(corner => {
                    // 先应用子物体自身的旋转
                    const childRotatedX = corner.x * cosChild - corner.y * sinChild;
                    const childRotatedY = corner.x * sinChild + corner.y * cosChild;

                    // 再应用父物体的旋转
                    const rotatedX = childRotatedX * cosA - childRotatedY * sinA;
                    const rotatedY = childRotatedX * sinA + childRotatedY * cosA;

                    minX = Math.min(minX, rotatedX);
                    maxX = Math.max(maxX, rotatedX);
                });

                // 调试信息
                // console.log(`子物体 ${child.name}: 自身旋转${child.eulerAngles.z}°, 位置(${childPos.x}, ${childPos.y})`);
            }
        });

        // console.log("最终水平边界:", { minX, maxX, width: maxX - minX });
        return { minX, maxX };
    }

}

window["JiuJiuXiaoDongWu_GameData"] = JiuJiuXiaoDongWu_GameData;